/*
 * DbAccess.h
 *
 *  Created on: Jan 28, 2013
 *      Author: root
 */

#ifndef DBACCESS_H_
#define DBACCESS_H_

#include "utils.h"
#include "smart_lock.h"
#include "sqlite3.h"
#include "mysql/mysql.h"
#include "../Svr_log.h"

/**
 * db vodconnection table define
 *
 * sql define
 * create connecton table,and table index
 * flag:failure 0, success 1
 * status:session live AUTH_WAIT 0->1,AUTH completed 2,AUTH_DISCONN_WAIT 3->4,AUTH_DISCONN completed 5
 * */
struct vodconnection
{
	/**
	 * table member
	 */
    int id;
    int Node_Id;
    int Conn_Id;
    char CleintIP[64];
    char SessionId[128];
    char File_Name[4096];
    char Url[4096];
    long long Total_KB;
    int Total_Secs;
    char CreatDateTime[64];
   	long SessionBeginTime;
   	long SessionEndTime;
	int flag;
	int status;

	/**
	 * init flag
	 */
    int fit_flag;

    vodconnection ()
    {
        id = 0;
        Node_Id = 0;
        Conn_Id = 0;
        memset(CleintIP,'\0',sizeof(CleintIP));
		memset(SessionId,'\0',sizeof(SessionId));
		memset(File_Name,'\0',sizeof(File_Name));
		memset(Url,'\0',sizeof(Url));
		Total_KB = 0;
		Total_Secs = 0;
        memset(CreatDateTime,'\0',sizeof(CreatDateTime));
        SessionBeginTime = 0;
        SessionEndTime = 0;
		flag = 0;
		status = 0;

		/**
		 * fit_flag:1,means struct data has been seted.
		 */
        fit_flag = 0;
    }
};

/*
 *
 * db access class
 */
class DbAccess {
public:
	DbAccess();
	virtual ~DbAccess();

	  int init(const char * dbpath,Svr_log * psvrlog);
	  int connectodb();
	  int execnosql(const char * sqlstr);
	  int querryvodconnection(const char * sqlstr,vodconnection * pRow);

	  /*
	   * row buf
	   */
	  int alloc_vodconnection_row_buf(vodconnection ** pRow);
	  void reset_vodconnection_row_buf(vodconnection * pRow);
	  void free_vodconnection_row_buf(vodconnection * pRow);


protected:
	  int create_db();
	  int db_sqlite_exec(const char * sqlstr);
	  int db_sqlite_querry_vodconnection(const char * sqlstr,vodconnection * pRow);

private:
	  /*
	   *  /path/name.db:sqlite database file
	   * */
	  char dbsvr[1024];
	  int open_flag;

	  /*lock*/
	  smart_lock dblock;

	  /*
	   * table buf
	   */
	  stack<vodconnection * > free_table_pool;
	  smart_lock table_pool_lock;

	  /**
	   * svr log
	   */
	  Svr_log    * pSvrlog;
};

#endif /* DBACCESS_H_ */
